package com.lanyeo.liver

import android.Manifest
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.accessibility.AccessibilityManager
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.lanyeo.liver.databinding.ActivityMainBinding
import com.lanyeo.liver.util.Zip
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.zip.ZipInputStream

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private var permissionCheckMask = 0x0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        iniView()
    }

    /**
     * 申请录屏权限
     */
    private val recordScreenLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val intent = Intent()
            intent.action = MessageReceiver.MSG
            intent.setPackage(packageName)
            intent.putExtra("code", result.resultCode)
            intent.putExtra("data", result.data)
            intent.putExtra("type", WorkService.MessageType.RECORD.toString())
            sendBroadcast(intent)
            setToBackground()
        } else {
            Toast.makeText(this, R.string.toast_request_permission_fail, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 申请通知权限
     */
    private val requestNoticePermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
        if (!isGranted) {
            Toast.makeText(this, R.string.toast_request_permission_fail, Toast.LENGTH_SHORT).show()
            binding.switchNotice.isChecked = false
        }
    }
    /**
     * 查看是否开启了通知权限
     */
    private fun checkNoticePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val hadNoticePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
            if (!hadNoticePermission) {
                binding.switchNotice.setOnCheckedChangeListener { _, isChecked ->
                    if (isChecked) {
                        requestNoticePermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
                    }
                }
            } else {
                permissionCheckMask = permissionCheckMask or PERMISSION_NOTICE
            }
        } else {
            permissionCheckMask = permissionCheckMask or PERMISSION_NOTICE
        }

        binding.switchNotice.isChecked = (permissionCheckMask and PERMISSION_NOTICE == PERMISSION_NOTICE)
    }

    /**
     * 判断是否开启了无障碍服务
     */
    private fun grantedAccessibilityService(): Boolean {
        val accessibilityManager = getSystemService(AccessibilityManager::class.java)
        val enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)
        for (service in enabledServices) {
            if (service.id.equals(packageName + "/." + WorkService::class.java.simpleName)) {
                return true
            }
        }
        return false
    }

    /**
     * 开启无障碍服务
     */
    private fun openAccessibilityService() {
        try {
            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        } catch (e: Exception) {
            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
            e.printStackTrace()
        }
    }

    /**
     * 检查是否需要开启无障碍服务
     */
    private fun checkAccessibilityPermission() {
        val hadAccessibilityPermission = grantedAccessibilityService()
        binding.switchAccess.isChecked = hadAccessibilityPermission
        if (hadAccessibilityPermission) {
            permissionCheckMask = permissionCheckMask or PERMISSION_ACCESS
            return
        }
        binding.switchAccess.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                if (checkAppData()) {
                    AlertDialog.Builder(this)
                        .setMessage(R.string.open_access_first)
                        .setNegativeButton("取消") { dialogInterface: DialogInterface, _ ->
                            dialogInterface.dismiss()
                            binding.switchAccess.isChecked = false
                        }.setPositiveButton("开启") { _: DialogInterface, _ ->
                            openAccessibilityService()
                        }.create().show()
                } else {
                    AlertDialog.Builder(this)
                        .setMessage(R.string.update_app_data_first)
                        .setNegativeButton("取消") { dialogInterface: DialogInterface, _ ->
                            dialogInterface.dismiss()
                            binding.switchAccess.isChecked = false
                        }.setPositiveButton("开启") { _: DialogInterface, _ ->
                            updateAppData()
                        }.create().show()
                }
            }
        }
    }

    /**
     * 检查是否开启悬浮窗权限
     */
    private fun checkFlowWindowPermission() {
        val hadFlowWindowPermission = Settings.canDrawOverlays(this)
        binding.switchFlow.isChecked = hadFlowWindowPermission
        if (hadFlowWindowPermission) {
            permissionCheckMask = permissionCheckMask or PERMISSION_FLOW
            return
        }
        binding.switchFlow.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + packageName))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                startActivity(intent)

            }
        }
    }

    /**
     * 检查数据包是否存在
     */
    private fun checkAppData(): Boolean {
        val unzipPath = applicationContext.getExternalFilesDir("bundle")!!
        if (unzipPath.isDirectory && unzipPath.exists() && unzipPath.listFiles().isNotEmpty()) {
            return true
        }
        return false
    }


    /**
     * 解压数据包
     */
    private fun unzipAppData(uri: Uri) {
        CoroutineScope(Dispatchers.IO).launch {
            val unzipPath = applicationContext.getExternalFilesDir("bundle")!!
            if (unzipPath.exists()) {
                unzipPath.deleteRecursively()
            }
            unzipPath.mkdirs()
            val zipInputStream = ZipInputStream(contentResolver.openInputStream(uri))
            val isOk = Zip.decompress(zipInputStream, unzipPath.absolutePath)
            withContext(Dispatchers.Main) {
                Toast.makeText(applicationContext, if (isOk) R.string.unzip_app_data_ok else R.string.unzip_app_data_fail, Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 选择APP外置数据包
     */
    private val selectAppDataLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val uri = result.data?.data ?: return@registerForActivityResult
            Log.d(TAG, "select app data. $uri")
            unzipAppData(uri)
        } else {
            Toast.makeText(this, R.string.none_select_app_data, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 更新数据包
     */
    private fun updateAppData() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*"
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        selectAppDataLauncher.launch(intent)
    }

    private fun iniView() {
        checkNoticePermission()
        checkFlowWindowPermission()
        checkAccessibilityPermission()
        binding.btnStartHelper.setOnClickListener {
            if ((permissionCheckMask and PERMISSION_ALL) != PERMISSION_ALL) {
                Toast.makeText(this, R.string.permission_tips, Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val mediaProjectionManager = getSystemService(MediaProjectionManager::class.java) //通过管理者，创建录屏请求，通过Intent
            val captureIntent: Intent = mediaProjectionManager.createScreenCaptureIntent() //将请求码作为标识一起发送，调用该接口，需有返回方法
            recordScreenLauncher.launch(captureIntent)
        }

        binding.btnUpdateAppData.setOnClickListener {
            updateAppData()
        }
    }

    //返回主界面开始录屏，相当于home键
    private fun setToBackground() { //主页面的Intent
        val home = Intent(Intent.ACTION_MAIN) //设置清除栈顶的启动模式
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) //匹配符号
        home.addCategory(Intent.CATEGORY_HOME) //转换界面，隐式匹配，显示调用
        startActivity(home)
    }

    override fun onStart() {
        super.onStart()
        permissionCheckMask = 0x0
        checkNoticePermission()
        checkAccessibilityPermission()
        checkFlowWindowPermission()
    }

    companion object {
        const val TAG = "MainActivity"
        const val PERMISSION_NOTICE = 0x1
        const val PERMISSION_ACCESS = 0x2
        const val PERMISSION_FLOW = 0x4
        const val PERMISSION_ALL = 0x7
    }
}